package com.huang.adapter;

public class ObjectAdapter {
    public static void main(String[] args) {
        Computer computer = new Computer();
        SDCard sdCard = new SDCardImpl();
        String s = computer.readSD(sdCard);//计算机只能适配SD卡接口，需要来个转换
        System.out.println(s);

        System.out.println("======================");
        //使用该电脑读取TF卡中的内容，传入TFCard，在Adapter上做个转换，
        SDAdapterTF2 sdAdapterTF2 = new SDAdapterTF2(new TFCardImpl());
        String s1 = computer.readSD(sdAdapterTF2);
        System.out.println(s1);

    }
}

/**
 * 不像类适配器，不用使用继承+实现，通过引入对象，设置全局变量来进行赋值
 */
class SDAdapterTF2 implements SDCard {

    //采用聚合，声明适配者类
    private TFCard tfCard;

    public SDAdapterTF2(TFCard tfCard) {
        this.tfCard = tfCard;
    }

    @Override
    public String readSD() {
        System.out.println("adapter read TF card");
        return tfCard.readTF();
    }

    @Override
    public void writeSD(String msg) {
        System.out.println("adapter writer sd card");
        tfCard.writeTF(msg);
    }
}

/**
 * 适配者接口
 */
interface TFCard {
    String readTF();

    void writeTF(String msg);
}

/**
 * 适配者类
 */
class TFCardImpl implements TFCard {

    @Override
    public String readTF() {
        String msg = "TFCard read msg: hello world TFCard";
        return msg;
    }

    @Override
    public void writeTF(String msg) {
        System.out.println("TFCard write msg: " + msg);
    }
}

/**
 * 目标接口
 */
interface SDCard {
    String readSD();

    void writeSD(String msg);
}

class SDCardImpl implements SDCard {

    @Override
    public String readSD() {
        String msg = "SDCard read msg: hello world SDCard";
        return msg;
    }

    @Override
    public void writeSD(String msg) {
        System.out.println("SDCard write msg: " + msg);
    }
}

class Computer {
    //从SD卡中读取数据
    public String readSD(SDCard sdCard) {
        if (sdCard == null) {
            throw new NullPointerException("sd card is null");
        }
        return sdCard.readSD();
    }

}

